﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.Security;

namespace AIS.SharePoint.AspNetFBA.Layouts.AIS.SharePoint.AspNetFBA
{
    public partial class Settings : LayoutsPageBase, System.Web.UI.IPostBackEventHandler
    {
        private const string _SAVECOMMAND = "Save";
        private const string _CANCELCOMMAND = "Cancel";

        /// <summary>
        /// This page requires site administrator.
        /// </summary>
        protected override bool RequireSiteAdministrator
        {
            get
            {
                return true;
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            try
            {
                // Create ribbon events for each supported command
                List<IRibbonCommand> CommandList = new List<IRibbonCommand>();
                CommandList.Add(new SPRibbonPostBackCommand("AIS.SharePoint.AspNetFAB.Ribbon.Edit.Commit.Publish", this, _SAVECOMMAND, null, "true"));
                CommandList.Add(new SPRibbonPostBackCommand("AIS.SharePoint.AspNetFAB.Ribbon.Edit.Commit.Cancel", this, _CANCELCOMMAND, null, "true"));

                Code.Ribbon.ActivateRibbon(this.Page, CommandList, sectionBottomButtons, Code.RibbonType.CommitRibbon);

                base.OnPreRender(e);
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                CheckRights();
                if (!IsPostBack)
                {
                    // Verify FBA is setup correctly
                    try
                    {
                        Roles.GetAllRoles();
                    }
                    catch
                    {
                        lblSetupStatus.Text = Code.Common.GetLocalizedResource("$Resources:Page_Settings_RoleConfigError");
                    }

                    try
                    {
                        Code.Claims ClaimHandler = new Code.Claims();
                        ClaimHandler.MembeshipProvider.GetNumberOfUsersOnline();
                    }
                    catch
                    {
                        lblSetupStatus.Text = Code.Common.GetLocalizedResource("$Resources:Page_Settings_MembershipConfigError");
                    }

                    Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);
                    chkAutoGenWelcomeEMail.Checked = Settings.AutoGenWelcomeEMail;
                    chkAutoGenPassword.Checked = Settings.AutoGenNewUserPassword;
                    chkEnablePasswordReset.Checked = Settings.EnableResetPassword;

                    txtWelcomeEMailSubjectLine.Text = Settings.WelcomeEMailSubject;
                    txtWelcomeEMailBody.Text = Settings.WelcomeEMailBody;
                    chkWelcomeEMailIsHTML.Checked = Settings.WelcomeEMailIsHTML;

                    txtResetEMailSubjectLine.Text = Settings.ResetEMailSubject;
                    txtResetEMailBody.Text = Settings.ResetEMailBody;
                    chkResetEMailIsHTML.Checked = Settings.ResetEMailIsHTML;

                    // No password reset if not enabled at the FBA providerlevel
                    try
                    {
                        chkEnablePasswordReset.Visible = System.Web.Security.Membership.EnablePasswordReset;
                    }
                    catch { chkEnablePasswordReset.Visible = false; }

                    chkAutoGenPassword.Focus();
                }

                sectionWelcomeEMailSettings.Visible = chkAutoGenWelcomeEMail.Checked;
                sectionResetEMailContent.Visible = chkEnablePasswordReset.Checked;
            }
            catch (System.UnauthorizedAccessException)
            {
                SPUtility.Redirect(SPUtility.AccessDeniedPage, SPRedirectFlags.RelativeToLayoutsPage, Context);
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Rendering);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            Save();
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            try
            {
                SPRibbonPostBackEvent RibbonEvent = SPRibbonPostBackCommand.DeserializePostBackEvent(eventArgument);
                string EventId = RibbonEvent.Id;

                if (string.Equals(EventId, _SAVECOMMAND, StringComparison.InvariantCultureIgnoreCase))
                {
                    Save();
                }
                else if (string.Equals(EventId, _CANCELCOMMAND, StringComparison.InvariantCultureIgnoreCase))
                {
                    Code.Common.ClosePage();
                }
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }

        private void Save()
        {
            try
            {
                // Do nothing for invalid pages
                Page.Validate();
                if (!Page.IsValid) { return; }

                Code.ConfigSettings Settings = new Code.ConfigSettings(SPContext.Current.Web);

                Settings.AutoGenWelcomeEMail = chkAutoGenWelcomeEMail.Checked;
                Settings.AutoGenNewUserPassword = chkAutoGenPassword.Checked;
                Settings.EnableResetPassword = chkEnablePasswordReset.Checked;

                Settings.WelcomeEMailSubject = txtWelcomeEMailSubjectLine.Text;
                Settings.WelcomeEMailBody = txtWelcomeEMailBody.Text;
                Settings.WelcomeEMailIsHTML = chkWelcomeEMailIsHTML.Checked;

                Settings.ResetEMailSubject = txtResetEMailSubjectLine.Text;
                Settings.ResetEMailBody = txtResetEMailBody.Text;
                Settings.ResetEMailIsHTML = chkResetEMailIsHTML.Checked;

                Settings.Update();

                Code.Common.ClosePage();
            }
            catch (Exception ex)
            {
                Code.Log.Error(ex, Microsoft.SharePoint.Administration.TraceSeverity.High, Code.Log.Category.Processing);
                SPUtility.TransferToErrorPage(ex.Message);
            }
        }
    }
}
